package com.tangding.service.dao.user;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.springframework.stereotype.Repository;

import com.tangding.common.exception.GException;
import com.tangding.common.logx.LogHelp;
import com.tangding.common.utils.Utils;
import com.tangding.config.Config;
import com.tangding.service.db.BaseMongoRepository;
import com.tangding.service.db.MongoDBOption;
import com.tangding.service.entity.user.User;

/**
 * @description 
 *
 * @author Ranger
 * @version 2016年8月13日_下午3:40:06
 *
 */
@Repository
public class UserRepository extends BaseMongoRepository<User, Serializable> {
	
	private Map<String, User> allAvailableUser = new HashMap<>();
	private Map<String, User> allUnavailableUser = new HashMap<>();
	
	@Override
	protected void afterInitClient() {
		option = new MongoDBOption("ACCOUNT", "user");
		
		try {
			List<User> users = findAll();
			if (users != null) {
				users.forEach(user->{
					if (user.isAvailable() || user.isAvailable() == null) {
						allAvailableUser.put(user.getUid(), user);
					}else {
						allUnavailableUser.put(user.getUid(), user);
					}
				});
			}
		} catch (GException e) {
			LogHelp.doLogAppErr(e);
			System.exit(-1);
			return;
		}
	}
	
	public Map<String, User> getUserMap() {
		return allAvailableUser;
	}
	
	public User getUserByUid(String uid) {
		return allAvailableUser.get(uid);
	}
	
	public void addUser(User user) throws GException {
		allAvailableUser.put(user.getUid(), user);
		
		if (Config.godAccount.equals(user.getUid())) {
			return;
		}
		save(user);
	}
	
	public void updateUser(User user) throws GException {
		allAvailableUser.put(user.getUid(), user);
		
		if (Config.godAccount.equals(user.getUid())) {
			return;
		}
		update(user, new Document("uid", user.getUid()));
	}
	
	public void setAvailable(User user) {
		Boolean available = user.isAvailable();
		if (available != null && available) {//设置成可用
			allAvailableUser.put(user.getUid(), user);
			allUnavailableUser.remove(user.getUid());
		}else {//设置成不可用
			allUnavailableUser.put(user.getUid(), user);
			allAvailableUser.remove(user.getUid());
		}
		update(user, new Document("uid", user.getUid()));
	}
	
	public User findUsersByUid(String username) throws GException {
		Document condition = new Document();
		condition.put("uid", username);
		User data = findOne(condition);
		return data;
	}
	
	public User findUsersByUidAndPwd(String username, String pwd) throws GException {
		Document condition = new Document();
		condition.put("uid", username);
		String password = Utils.getMD5(Utils.getMD5(pwd));
		condition.put("password", password);
		User data = findOne(condition);
		return data;
	}
}
